package cn.edu.nju.software.action.transaction;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.bean.show.BookItemInOrder;
import cn.edu.nju.software.bean.show.UserShow;
import cn.edu.nju.software.bean.storage.Order;
import cn.edu.nju.software.service.intf.TransactionService;
import cn.edu.nju.software.service.intf.UserService;
import cn.edu.nju.software.util.Constants;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class SettleCartAction extends ActionSupport implements SessionAware {

	private String addressRadio;
	private String name;
	private String area;
	private String address;
	private String zipCode;
	private String phone;
	private boolean saveAddress;
	private BigDecimal charge;
	private int orderID;
	private UserService userService;
	private TransactionService transactionService;
	private Map<String, Object> session;

	public void setAddressRadio(String addressRadio) {
		this.addressRadio = addressRadio;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setArea(String area) {
		this.area = area;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public void setSaveAddress(boolean saveAddress) {
		this.saveAddress = saveAddress;
	}

	public BigDecimal getCharge() {
		return charge;
	}

	public void setCharge(BigDecimal charge) {
		this.charge = charge;
	}

	public int getOrderID() {
		return orderID;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setTransactionService(TransactionService transactionService) {
		this.transactionService = transactionService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	@Override
	public String execute() throws Exception {
		@SuppressWarnings("unchecked")
		List<BookItemInOrder> cart = (List<BookItemInOrder>) session.get(Constants.SESSION_CART);
		Order order;
		UserShow userOld = (UserShow) session.get(Constants.SESSION_USER);
		if (addressRadio.equals("")) {
			String s = Constants.ADDRESS_SEPARATOR;
			String encodedAddress = name + s + area + s + address + s + zipCode + s + phone;
			order = new Order(0, userOld.getUserID(), charge, 0, encodedAddress, null, null, null);
			if (saveAddress) {
				userOld.setAddress(encodedAddress);
				userService.updateUser(userOld.getUser());
			}
		} else {
			order = new Order(0, userOld.getUserID(), charge, 0, addressRadio, null, null, null);
		}
		orderID = transactionService.submitOrder(order, cart);
		cart.clear();
		return SUCCESS;
	}
}
